package com.byron.pss.template;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;

/**
 * 处理javabean的统一类,用来获取单行数据
 * @author Byron
 *
 */
public class BeanHandler<T> implements IResultHandler<T> {

	private Class<T> type;

	public BeanHandler(Class<T> type) {
		this.type = type;
	}

	@Override
	public T handle(ResultSet rs) throws Exception {
		//有值就返回该对象，没有就返回null
		if (rs.next()) {
			// 通过内省机制，给T的对象赋值
			T obj = (T) type.newInstance();
			BeanInfo beanInfo = Introspector.getBeanInfo(type, Object.class);
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor ps : pds) {
				// 拿到setter方法，调用赋值:这里就要求实体严格遵循javabean规范，否则会出错
				ps.getWriteMethod().invoke(obj, rs.getObject(ps.getName()));
			}
			return obj;
		}else{
			return null;
		}
	}
}
